var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var hyxRouter = require('./routes/hyx');
var yzxRouter = require('./routes/yzx');
var kjqRouter = require('./routes/kjq');
var tmbRouter = require('./routes/tmb');

var {     setAccessToken,     // 定义短Token
  setRefreshToken,    // 定义长Token
  testAccessToken,    // 验证短token是否过期
  testRefreshToken  // 验证长token是否过期
}=require('./token/index')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cors=require('cors')
var jwtExpress=require('express-jwt')

var app = express();
app.use(cors());

//白名单
app.use((req,res,next)=>{
  let token = req.headers.authorization
  console.log(token);
  
  console.log(req.path==='/login');
  if (req.path === '/hyx/login'
    || req.path === '/userid'
    || req.path === '/login1'
    || req.path === '/sign'
    || req.path === '/phoneCode'
    || req.path === '/password1'

    || req.path === '/hyx/code'
    || req.path === '/hyx/reg' 
    || req.path.includes('/upload')
  ) {//如果是登录或者获取短token则不做任何操作
    next()
  }
  else {//判断短token是否过期
    let tokenState = testAccessToken(token)
    if (tokenState.code === 200) {
      next()
    } else {//过期返回401状态码
      res.send({
        code: 409,
        msg: 'token过期'
      })
    }
  }
    
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/upload',express.static(path.join(__dirname, 'upload')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
// 路由接口
app.use('/hyx', hyxRouter);
app.use('/yzx', yzxRouter);
app.use('/tmb', tmbRouter);
app.use('/kjq', kjqRouter);
 

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
